import defineVP from '../../../src'
import { Router } from 'vitepress'


declare global {
  interface Window {
    eventCenterForAppNameVite: any
    __MICRO_APP_NAME__: string
    __MICRO_APP_ENVIRONMENT__: string
    __MICRO_APP_BASE_APPLICATION__: string
  }
}

// 与基座进行数据交互
function handleMicroData (router: Router) {
  // eventCenterForAppNameVite 是基座添加到window的数据通信对象
  if (window.eventCenterForAppNameVite) {
    // 主动获取基座下发的数据
    console.log('child-vite getData:', window.eventCenterForAppNameVite.getData())

    // 监听基座下发的数据变化
    window.eventCenterForAppNameVite.addDataListener((data: Record<string, unknown>) => {
      console.log('child-vite addDataListener:', data)

      if (data.path && typeof data.path === 'string') {
        data.path = data.path.replace(/^#/, '')
        // 当基座下发path时进行跳转
        // if (data.path && data.path !== router.currentRoute.value.path) {
        //   router.push(data.path as string)
        // }
      }
    })

    // 向基座发送数据
    setTimeout(() => {
      window.eventCenterForAppNameVite.dispatch({ myname: 'child-vite' })
    }, 3000)
  }

  router.onBeforeRouteChange = (some) => {
    if (window.eventCenterForAppNameVite) {
      // 发送全局数据，通知侧边栏修改菜单展示
      window.eventCenterForAppNameVite.setGlobalData({ name: 'child-vite' })
    }
  }
}

const microApp = ({ app, router }) => {
  if (typeof window !== "undefined") {
    console.log('微应用child-vite渲染了')
    console.log('child', router);
    
    handleMicroData(router);
    
    // 监听卸载操作
    window.addEventListener('unmount', function () {
      app.unmount()
      // 卸载所有数据监听函数
      window.eventCenterForAppNameVite?.clearDataListener()
      console.log('微应用child-vite卸载了')
    })
  }
}


/** @type {import('vitepress').Theme} */
export default defineVP(microApp);